import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../routes/app_pages.dart';
import '../../../data/services/api_service.dart';
import '../../../data/services/user_service.dart';
import '../../../data/services/base_service.dart';

class LoginController extends GetxController {
  // 表单控制器
  final phoneController = TextEditingController();
  final passwordController = TextEditingController();

  // 响应式变量
  final isPasswordVisible = false.obs;
  final isAgreementChecked = false.obs;
  final isLoading = false.obs;
  final loginError = ''.obs; // 登录错误信息

  // 系统配置相关
  final isLoadingSysConfig = true.obs;
  final userAgreementLink = ''.obs;
  final privatePolicyLink = ''.obs;
  final userAgreement = ''.obs;
  final privatePolicy = ''.obs;

  // 表单验证
  final formKey = GlobalKey<FormState>();

  // 服务实例 - GetX规范
  final ApiService _apiService = Get.find<ApiService>();
  final UserService _userService = Get.find<UserService>();
  final BaseService _baseService = BaseService();

  @override
  void onInit() {
    super.onInit();
    // 预填充测试账号（开发环境）
    // phoneController.text = '13858003079';
    // phoneController.text = '15563581678';

    // passwordController.text = 'WAzqSU@96371';
    if (kDebugMode) {
      // phoneController.text = '15563581678';
      phoneController.text = '13858003079';
      passwordController.text = 'WAzqSU@96371';
    }

    /// - 手机号: 15199999999
    /// - 密码: WAjmSU@96371
    // phoneController.text = '15199999999';
    // passwordController.text = 'WAjmSU@96371';

    isAgreementChecked.value = false; // 默认不勾选

    // 🚀 自动获取系统配置
    _loadSysConfig();
  }

  @override
  void onClose() {
    phoneController.dispose();
    passwordController.dispose();
    super.onClose();
  }

  /// 获取系统配置（用户协议和隐私政策链接）
  Future<void> _loadSysConfig() async {
    try {
      isLoadingSysConfig.value = true;
      print('🔧 开始获取系统配置...');

      final response = await _apiService.getSysConfig();
      final data = response['data'] as Map<String, dynamic>?;

      if (data != null) {
        // 保存协议链接
        userAgreementLink.value = data['userAgreementLink']?.toString() ?? '';
        privatePolicyLink.value = data['privatePolicyLink']?.toString() ?? '';

        // 保存协议内容（备用）
        userAgreement.value = data['userAgreement']?.toString() ?? '';
        privatePolicy.value = data['privatePolicy']?.toString() ?? '';

        print('✅ 系统配置获取成功');
        print('📄 用户协议链接: ${userAgreementLink.value}');
        print('🔒 隐私政策链接: ${privatePolicyLink.value}');
      } else {
        print('❌ 系统配置数据为空');
      }
    } catch (e) {
      print('❌ 获取系统配置失败: $e');
      // 设置默认值，确保不影响登录流程
      userAgreementLink.value = 'www.wasu.com';
      privatePolicyLink.value = 'www.wasu.com';
    } finally {
      isLoadingSysConfig.value = false;
    }
  }

  /// 打开用户协议
  void openUserAgreement() {
    if (userAgreementLink.value.isNotEmpty) {
      Get.toNamed(
        Routes.WEBVIEW,
        arguments: {'url': userAgreementLink.value, 'title': '用户协议'},
      );
    } else {
      print('用户协议链接为空');
    }
  }

  /// 打开隐私政策
  void openPrivatePolicy() {
    if (privatePolicyLink.value.isNotEmpty) {
      Get.toNamed(
        Routes.WEBVIEW,
        arguments: {'url': privatePolicyLink.value, 'title': '隐私政策'},
      );
    } else {
      print('隐私政策链接为空');
    }
  }

  /// 获取协议文本（用于UI显示）
  String get agreementText {
    if (isLoadingSysConfig.value) {
      return '正在加载协议...';
    }
    return '我已阅读并同意《用户协议》和《隐私政策》';
  }

  // 切换密码可见性
  void togglePasswordVisibility() {
    isPasswordVisible.value = !isPasswordVisible.value;
  }

  // 切换协议同意状态
  void toggleAgreement() {
    isAgreementChecked.value = !isAgreementChecked.value;
  }

  // 验证表单
  bool validateForm() {
    if (!formKey.currentState!.validate()) {
      return false;
    }

    if (!isAgreementChecked.value) {
      BotToast.showText(text: '请先阅读并同意用户协议或者隐私政策');
      return false;
    }

    return true;
  }

  // 登录
  Future<void> login() async {
    if (!validateForm()) return;

    try {
      isLoading.value = true;
      loginError.value = ''; // 清除之前的错误信息

      final phone = phoneController.text.trim();
      final password = passwordController.text.trim();

      // 调用登录API
      final loginData = await _apiService.login(
        phone: phone,
        password: password,
      );

      if (loginData != null) {
        // 保存登录信息到UserService和本地存储
        _userService.saveLoginInfo(loginData);

        // 设置全局认证信息（所有服务共享）
        final data = loginData['data'] as Map<String, dynamic>?;
        if (data != null) {
          final token = data['token'] as String?;
          final userInfo = data['miniUserInfoVO'] as Map<String, dynamic>?;
          final tenantId = userInfo?['tenantId'] as String?;

          if (token != null && tenantId != null) {
            _baseService.setAuth(token, tenantId);
            print('登录成功，已设置全局认证信息');
          }
        }

        // 检查是否需要修改密码
        final busiCode = loginData['busiCode'] as String?;
        if (busiCode == 'ModifyPassword') {
          // TODO: 弹窗提示修改密码
          print('需要修改密码');
          // 可以导航到修改密码页面
          // Get.toNamed(Routes.UPDATE_PWD);
          return;
        }

        // 登录成功，跳转到主页
        Get.offAllNamed(Routes.TABBAR);

        print('登录成功，TabBar将自动检查并刷新数据');
      }
    } catch (e) {
      print('登录失败: $e');

      // 根据错误类型显示不同的提示信息
      String errorMessage = '网络环境不佳，请稍后尝试';

      if (e.toString().contains('用户名或密码错误')) {
        errorMessage = '用户名或密码错误，请检查后重试';
      } else if (e.toString().contains('网络') || e.toString().contains('连接')) {
        errorMessage = '网络连接失败，请检查网络后重试';
      } else if (e.toString().contains('超时')) {
        errorMessage = '请求超时，请稍后重试';
      }

      loginError.value = errorMessage;
      BotToast.showText(text: errorMessage);
    } finally {
      isLoading.value = false;
    }
  }

  // 忘记密码
  void forgotPassword() {
    Get.toNamed(Routes.FORGOT_PWD);
  }

  // 手机号验证
  String? validatePhone(String? value) {
    if (value == null || value.isEmpty) {
      return '请输入手机号';
    }
    if (!RegExp(r'^1[3-9]\d{9}$').hasMatch(value)) {
      return '请输入正确的手机号';
    }
    return null;
  }

  // 密码验证
  String? validatePassword(String? value) {
    if (value == null || value.isEmpty) {
      return '请输入密码';
    }
    if (value.length < 6) {
      return '密码长度不能少于6位';
    }
    return null;
  }

  // 检查登录按钮是否可用
  bool get isLoginButtonEnabled {
    return phoneController.text.isNotEmpty &&
        passwordController.text.isNotEmpty &&
        isAgreementChecked.value &&
        !isLoading.value;
  }
}
